1
touch main.go
package main
import "fmt"
func main() {
fmt.Println(helloworld())
}
touch helloworld.go
package main
func helloworld() string {
return "hello world"
}
下command
go run main.go helloworld.go
同一層資料夾的go,package必須相同,例如範例兩隻package都是main
mkdir helloworld
mv helloworld.go ./helloworld
export GOPATH=/var/go1
vi ./helloworld/helloworld.go
package helloworld
func HelloWorld() string { // export必須為大寫
return "hello world"
}
vi main.go
package main
import (
"fmt"
"github.com/go-training/test/helloworld" // 通常以{網域名}{帳戶名}{專案名稱},一切皆以gopath的src下為路徑
)
func main() {
fmt.Println(helloworld.HelloWorld()) // 引入package name去調用其func
}
import "github.com/go-training/test/helloworld"
{package Name}.{method name}()
2
別名
import {alias} "github.com/go-training/test/helloworld"
{alias}.{method name}()
3
use dot
import . "github.com/go-training/test/helloworld"
{method name}()
此時package會到main.go同層,直接呼叫method即可使用不建議用此方法import,維護code會很麻煩
4
use underscore
vi ./helloworld/helloworld.go
package helloworld
import "fmt"
func init() {
fmt.Println("init helloworld")
}
func HelloWorld() string { // export必須為大寫
return "hello world"
}
vi main.go
package main
import (
"fmt"
_ "github.com/go-training/test/helloworld" // 通常以{網域名}{帳戶名}{專案名稱},一切皆以gopath的src下為路徑
)
func main() {
fmt.Println("eee") // 引入package name去調用其func
}